<?php
class OrdersController extends AppController {

	var $name = 'Orders';
	var $uses= array('Product','Youcart','Invoice','Member','InvoicesDetail');
	
	function index() {
		
		$id_user=$this->Session->read("tkid");
		$ip=getenv("REMOTE_ADDR");
		$shows=$this->Youcart->find('all',array('conditions'=>array(
														'Youcart.user_id'=>$id_user,
														'Youcart.session_you'=>$this->Session->id(),
														'Youcart.ip_you'=>$ip
														)));
		$this->set('shows',$shows);	
		//ma hoa don 
		$listId=$this->Invoice->find('list', array(
															'fields' => array('Invoice.id'),
															'recursive' => 0
															));
	 
	   if($listId){
	   		$this->set('idInvoice',max($listId));
		}else{
				$this->set('idInvoice','0');
			}
	   //thong tin ca nhan
	   $this->data=$this->Member->read(null,$this->Session->read("tkid"));		
	}
	function addInvoice() {
		
		$id_user=$this->Session->read("tkid");
		$ip=getenv("REMOTE_ADDR");
		//lay thong tin chi tiet san pham
		$spAll=$this->Youcart->find('all',array('conditions'=>array(
																		'Youcart.user_id'=>$id_user,
																		'Youcart.ip_you'=>$ip,
																		'Youcart.session_you'=>$this->Session->id()
																	)));
		
		$diengiai='';
		$i=0;
		foreach($spAll as $sp){
			$diengiai=$diengiai.'Mua '.$sp['Youcart']['quantity_product'].'&nbsp;' .$sp['Youcart']['name_product'].'<br>';
			
		}
		
		//add vao tabale invoices
		$invoices=array('Invoice'=>array(
										'code'=>$_POST['codeInvoice'],
										'id_user'=>$_POST['idMember'],
										'total_money'=>$_POST['total_money'],
										'interpretation'=>$diengiai,
										'name'=>$_POST['nameMember']
											));
		
		
		$this->Invoice->save($invoices);		
		$idInvoice=$this->Invoice->getLastInsertID();
		$idProduct=$_POST['idProducts'];
		
		$i=1;
		foreach($idProduct as $key){
			$cos[$i]=$this->Youcart->findByIdProduct($key);				
			$invoices_details[$i]=array(
							'InvoicesDetail'=>array(
									'id_invoice'=>$idInvoice,
									'id_user'=>$_POST['idMember'],
									'name_product'=>$cos[$i]['Youcart']['name_product'],
									'code_product'=>$cos[$i]['Youcart']['code_product'],
									'quantity_product'=>$cos[$i]['Youcart']['quantity_product'],
									'cost_product'=>$cos[$i]['Youcart']['cost_product']
									
									)
							);
			$i++;
		
		}
		
		$this->InvoicesDetail->saveall($invoices_details);
		$this->Youcart->deleteall($key);
		//pr($cos);
		//pr($hodon_sanpham);die();
		echo "<script>alert('".json_encode('Bạn đã mua hàng thành công')."');</script>";
		echo "<script>location.href='".System."/infors'</script>";	

	}

}
?>